package com.hd.crdao.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;

import com.hd.crdao.MainActivity;
import com.hd.crdao.R;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.UIUtils;

import java.util.ArrayList;
import java.util.List;

/**
 *
 *@author Programming
 *@date 2017/5/24 0024
 */

public class SplashActivity extends Activity {


    private static final int MY_PERMISSION_REQUEST_CODE = 101;
    /* private static final int SINPLE_PERMISSIONS_REQ_CODE = 102;*/
    private static final int REQUEST_PERMISSION_SETTING = 103;
    String[] permissions = new String[]{
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_SETTINGS,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private Handler mHandler = new Handler();
    private List<String> unCheckPermissions = new ArrayList<>();
    boolean flag = false;
    private int time;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            for (String permission1 : permissions) {
                if (checkSelfPermission(permission1) != PackageManager.PERMISSION_GRANTED) {
                    unCheckPermissions.add(permission1);
                }
            }
            if (unCheckPermissions.size() == 0) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        GoMainApp();
                    }
                }, 1500);
            } else {
                for (String permission : permissions) {
                    if (shouldShowRequestPermissionRationale(permission)) {
                        flag = true;
                        break;
                    }
                }
            }

            if (flag) {
                new AlertDialog.Builder(this)
                        .setMessage("为了保证应用能够正常使用,请前往设置如下权限:" +
                                "位置访问权限、相机权限、储存空间权限、拍照权限")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.fromParts("package", getPackageName(), null));
                                startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
                            }
                        }).show();
            } else {
                requestPermissions(permissions, MY_PERMISSION_REQUEST_CODE);
            }
        } else {
            GoMainApp();
        }
    }


    /**
     * 检查是否拥有指定的所有权限
     */
    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                // 只要有一个权限没有被授予, 则直接返回 false
                ALog.d(permission + "请求的结果是" + false);
                unCheckPermissions.add(permission);
                return false;
            }
        }
        return true;
    }

    /**
     * 第 3 步: 申请权限结果返回处理
     */
    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == MY_PERMISSION_REQUEST_CODE) {
            // 判断是否所有的权限都已经授予了
            if (checkPermissionAllGranted(permissions)) {
                GoMainApp();
            } else {
                if (time < 4 && !checkPermissionAllGranted(permissions)) {
                    requestPermissions(new String[]{permissions[0]}, MY_PERMISSION_REQUEST_CODE);
                    time++;
                    ALog.d("当前的次数是" + time);
                } else {
                    new AlertDialog.Builder(this)
                            .setMessage("为了保证应用能够正常使用,请前往设置如下权限:" +
                                    "位置访问权限、相机权限、储存空间权限")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    intent.setData(Uri.fromParts("package", getPackageName(), null));
                                    startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
                                }
                            }).show();
                }
            }

        }
    }


    private void GoMainApp() {
        startActivity(new Intent(UIUtils.getContext(), MainActivity.class));
        finish();
    }

    public String[] List2String(List<String> list) {
        if (!list.isEmpty()) {
            String[] strings = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                strings[i] = list.get(i);
            }
            return strings;
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PERMISSION_SETTING) {
            boolean checkPermissionAllGranted = checkPermissionAllGranted(permissions);
            if (checkPermissionAllGranted) {
                GoMainApp();
            } else {
                finish();
            }
        }

    }
}
